<!-- WatchExample.vue -->
<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'

// watch 示例
const id = ref(1)
const data = ref<any>(null)

watch(id, async (newId, oldId) => {
  console.log(`ID 从 ${oldId} → ${newId}`)
  try {
    const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${newId}`)
    data.value = await res.json()
  } catch (error) {
    console.error('请求失败:', error)
  }
}, { immediate: true })

// watchEffect 示例
const x = ref(0)
const y = ref(0)

watchEffect(() => {
  console.log(`角色坐标：(${x.value}, ${y.value})`)
})

// 模拟坐标变化
const moveRandomly = () => {
  x.value = Math.floor(Math.random() * 100)
  y.value = Math.floor(Math.random() * 100)
}
</script>

<template>
  <div class="watch-example">
    <div class="watch-demo">
      <h3>watch 示例</h3>
      <p>当前 ID: {{ id }}</p>
      <button @click="id++">切换 ID</button>
      <pre v-if="data">{{ JSON.stringify(data, null, 2) }}</pre>
    </div>
    
    <div class="watch-effect-demo">
      <h3>watchEffect 示例</h3>
      <p>坐标: ({{ x }}, {{ y }})</p>
      <button @click="moveRandomly">随机移动</button>
      <p>查看控制台输出</p>
    </div>
  </div>
</template>

<style scoped>
.watch-example {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-top: 10px;
}

.watch-demo, .watch-effect-demo {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}
</style>